//
//  FGImageMessageCellData.m
//  FGChatKit
//
//  Created by Henry on 2021/6/3.
//

#import "FGImageMessageCellData.h"
#import "FGPathTool.h"
#import "FGResources.h"
#import "FGChatHelper.h"
#import "FGNetworkHelper.h"

@implementation FGImageItem

- (NSString *)getImageFileName {
    NSString *suffix = @"";
    switch (_type) {
        case FGImageTypeThumb:
            suffix = @"_thumb";
            break;
        case FGImageTypeLarge:
            suffix = @"_large";
            break;
        default:
            break;
    }
    return [self.uuid stringByAppendingString:suffix];
}

- (NSString *)getImagePath:(NSString *)convsationId {
    return [FGChatHelper pathConvImage:convsationId name:[self getImageFileName]];
}

- (void)downloadPath:(NSString *)path progress:(FGDownloadProgress)progress succ:(FGSucc)succ fail:(FGFail)fail {
    
    [FGNetworkHelper downloadWithURL:self.url filePath:path progress:^(int64_t completedCount, int64_t totalCount) {
        CGFloat received = (CGFloat)completedCount;
        NSUInteger pp = (NSUInteger)(received/totalCount * 100);
        if (progress) {
            progress(pp);
        }
    } success:^(NSString * _Nonnull filePath) {
        if (succ) {
            succ();
        }
    } failure:^(NSError * _Nonnull error) {
        if (fail) {
            fail(10001, @"server download fail");
        }
    }];
}

@end

@interface FGImageMessageCellData ()

@property (nonatomic, assign) BOOL isDownloading;

@end

@implementation FGImageMessageCellData


- (instancetype)initWithDirection:(FGMsgDirection)direction {
    self = [super initWithDirection:direction];
    if (self) {
        self.thumbProgress = 0;
    }
    return self;
}

+ (NSString *)reuseIdentifier {
    return @"FGImageMessageCell";
}

- (CGSize)contentSize {
    CGSize size = CGSizeZero;
    for (FGImageItem *item in self.items) {
        if (item.type == FGImageTypeThumb) {
            size = item.size;
            break;
        }
    }
    if (CGSizeEqualToSize(size, CGSizeZero)) {
        for (FGImageItem *item in self.items) {
            if (item.type == FGImageTypeLarge) {
                size = item.size;
                break;
            }
        }
    }
    if (CGSizeEqualToSize(size, CGSizeZero)) {
        for (FGImageItem *item in self.items) {
            if(item.type == FGImageTypeOrigin) {
                size = item.size;
                break;
            }
        }
    }
    if (CGSizeEqualToSize(size, CGSizeZero)) {
        return CGSizeMake(44, 44);
    }
    return [FGChatHelper getThumbSizeFromOrigin:size];
}

- (void)setItems:(NSMutableArray<FGImageItem *> *)items {
    if (!self.uuid) {
        NSAssert(NO, @"必须先设置uuid");
    }
    for (FGImageItem *item in items) {
        item.uuid = self.uuid;
    }
    _items = items;
}

- (FGImageItem *)getImageItem:(FGImageType)type {
    for (FGImageItem *item in self.items) {
        if (item.type == type) {
            return item;
        }
    }
    return nil;
}

- (void)loadImage {
    FGImageItem *item = [self getImageItem:FGImageTypeThumb];
    if (item) {
        [self loadImage:FGImageTypeThumb];
        return;
    }
    FGImageItem *itemLarge = [self getImageItem:FGImageTypeLarge];
    if (itemLarge) {
        [self loadImage:FGImageTypeLarge];
        return;
    }
    [self loadImage:FGImageTypeOrigin];
}

- (void)loadImage:(FGImageType)type {
    if (self.thumbImage) {
        return;
    }
    FGImageItem *item = [self getImageItem:type];
    if (!item) {
        return;
    }
    if (!self.conversationId) {
        NSAssert(NO, @"必须设置conversationId，方便管理会话文件");
    }
    NSString *path = [item getImagePath:self.conversationId];
    BOOL isExist = [FGPathTool isExistFile:path];
    if (isExist) {
        self.thumbImage = [UIImage imageWithContentsOfFile:path];
    } else {
        if (self.isDownloading) {
            return;
        }
        __weak typeof(self) ws = self;
        [item downloadPath:path progress:^(NSUInteger progress) {
            [ws updateProgress:progress withType:type];
        } succ:^{
            ws.isDownloading = NO;
            [ws updateProgress:100 withType:type];
            ws.thumbImage = [UIImage imageWithContentsOfFile:path];
        } fail:^(int code, NSString * _Nonnull msg) {
            ws.isDownloading = NO;
            ws.thumbImage = [FGResources getImageFromMessage:@"placeholder_image"];
        }];
    }
}

- (void)updateProgress:(NSUInteger)progress withType:(FGImageType)type {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (type == FGImageTypeThumb) {
            self.thumbProgress = progress;
        }
        if (type == FGImageTypeLarge) {
            
        }
        if (type == FGImageTypeOrigin) {
            
        }
    });
}

- (id)getThumbImage {
    FGImageItem *item = [self getImageItem:FGImageTypeThumb];
    if (!item) {
        return nil;
    }
    NSString *path = [item getImagePath:self.conversationId];
    BOOL isExist = [FGPathTool isExistFile:path];
    if (isExist) {
        return [UIImage imageWithContentsOfFile:path];
    }
    return [NSURL URLWithString:item.url];
}

- (id)getLargeImage {
    FGImageItem *item = [self getImageItem:FGImageTypeLarge];
    if (!item) {
        return nil;
    }
    NSString *path = [item getImagePath:self.conversationId];
    BOOL isExist = [FGPathTool isExistFile:path];
    if (isExist) {
        return [UIImage imageWithContentsOfFile:path];
    }
    return [NSURL URLWithString:item.url];
}

- (id)getOriginImage {
    FGImageItem *item = [self getImageItem:FGImageTypeOrigin];
    if (!item) {
        return nil;
    }
    NSString *path = [item getImagePath:self.conversationId];
    BOOL isExist = [FGPathTool isExistFile:path];
    if (isExist) {
        return [UIImage imageWithContentsOfFile:path];
    }
    return [NSURL URLWithString:item.url];
}

- (id)getPreviewImage {
    id image = [self getOriginImage];
    if (image) {
        return image;
    }
    image = [self getLargeImage];
    if (image) {
        return image;
    }
    image = [self getThumbImage];
    if (image) {
        return image;
    }
    return [[UIImage alloc] init];
}

@end
